package net.huazai.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.UUID;

/**
 * @author 11987
 */
@Slf4j
public class CommonUtil {

    /**
     * 获取客户端 ip
     * @param request 请求对象
     * @return  ip
     */
    public static String getRemoteIpAddr(HttpServletRequest request) {
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    // 根据网卡取本机配置的 IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    if (inet != null){
                        ipAddress = inet.getHostAddress();
                    }
                }
            }
            // 对于通过多个代理的情况，第一个 IP 为客户端真实 IP,多个 IP 按照 ',' 分割
            if (ipAddress != null && ipAddress.length() > 15) {
                // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

    /**
     * MD5 加密
     * @param data 加密数据
     * @return 加密结果
     */
    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
            }

            return sb.toString().toUpperCase();
        } catch (Exception exception) {
        }
        return null;
    }

    /**
     * 获取验证码随机数
     * @param length 验证码长度
     * @return 验证码
     */
    public static String getRandomCode(int length){

        String sources = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for(int j=0; j<length; j++){
            sb.append(sources.charAt(random.nextInt(9)));
        }
        return sb.toString();
    }

    /**
     * 获取当前时间戳
     * @return 时间戳
     */
    public static long getCurrentTimestamp(){
        return System.currentTimeMillis();
    }

    /**
     * 生成 UUID
     * @return UUID
     */
    public static String generateUuid(){
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 加密串
     */
    private static final String SECRET_STRING = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    /**
     * 生成指定长度随机串
     * 这里直接参考 Md5Crypt 源码实现
     * @param num 长度
     * @return 随机串
     */
    public static String getRandomSalt(int num) {
        //生成随机数字和字母,符号
        Random random = new Random();
        StringBuilder saltString = new StringBuilder(num);
        for (int i = 1; i <= num; ++i) {
            saltString.append(SECRET_STRING.charAt(random.nextInt(SECRET_STRING.length())));
        }
        return saltString.toString();
    }

    /**
     * 返回响应给前端
     * @param response 响应对象
     * @param object 响应数据
     */
    public static void sendResponse(HttpServletResponse response, Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        // 设置响应头
        response.setContentType("application/json; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            // 写出响应
            writer.print(objectMapper.writeValueAsString(object));
            log.info("返回响应给前端数据：{}", objectMapper.writeValueAsString(object));
            // flush
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("返回响应给前端异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}

